/**
 * Created by lixinkun on 2017/7/9.
 */
'use strict';

import * as types from './actionTypes';
import fetchUrl from '../constants/fetchUrl';
import fetchWithTimeout from '../utils/fetchWithTimeout';
import Toast from 'react-native-root-toast';
import px2dp from '../utils/px2dp';

function requestData() {
    return {
        type: types.FETCH_WEATHER_DATA_REQUEST,
    }
}

/**
 * 返回结果
 * @param json
 * @returns {{type, basic: (*|null), nowWeather: (*|null), suggestion: (*|null), aqi: (*|null), daily_forecast: (*|null)}}
 */
function receiveData(json) {
    return {
        type: types.FETCH_WEATHER_DATA_SUCCESS,
        basic: json.basic,
        nowWeather: json.now,
        suggestion: json.suggestion,
        aqi: json.aqi,
        daily_forecast: json.daily_forecast,
    }
}

/**
 * 返回获取到的图片链接
 * @param image
 * @returns {{type, backgroundImage: *}}
 */
function receiveImage(image) {
    return {
        type: types.FETCH_WEATHER_BACK_IMAGE_SUCCESS,
        backgroundImage: image,
    };
}

function fetchFailure() {
    return {
        type: types.FETCH_WEATHER_DATA_FAILURE,
    }
}

function isValidData(responseData) {
    if (responseData) {
        return true;
    }
    return false;
}

function fetchRaw(url, callBack){

    fetch(url)
        .then((response)=>{
            callBack(response);
        })
        .catch(function(error){
            console.error("error = " + error);
        })
};


/**
 * 获取网络天气数据
 * @param weatherId
 * @returns {function(*=)}
 */
export function fetchWeatherData(weatherId) {
    let url = fetchUrl.weatherBaseUrl + "weather/" + "?cityid=" + weatherId + "&key=" + fetchUrl.key;
    function fetchWeather(dispatch) {
        fetchWithTimeout(5000, fetch(url)
            .then(response => response.json())
            .then((json) => {
                let weatherInfo = json.HeWeather[0];
            if (isValidData(weatherInfo)) {
                dispatch(receiveData(weatherInfo));
            } else {
                dispatch(fetchFailure())
            }
            }).catch((error) => {
                console.log(error);
                Toast.show('获取数据失败', {position: px2dp(-80)});
            })
        );
    }

    return (
        dispatch => {
            dispatch(requestData());
            fetchWeather(dispatch);
        }
    )
}

/**
 * 获取每日背景图片
 */
export function fetchBackgroundImage() {
    let url = fetchUrl.weatherBackgroundUrl;
    function fetchImage(dispatch) {
        fetchWithTimeout(5000, fetch(url)
            .then((response) =>{
                response.text().then(function (res) {
                    dispatch(receiveImage(res));
                });
            })
            .catch((error)=> {
                console.log(error);
                Toast.show('获取数据失败', {position: px2dp(-80)});
            })
        );
    }

    return (
        dispatch => {
            dispatch(requestData());
            fetchImage(dispatch);
        }
    )
}